package com.cole.gx095.service.impl;

import com.cole.gx095.Repository.SalebillRepository;
import com.cole.gx095.domain.QueryData;
import com.cole.gx095.service.CostService;
import com.cole.gx095.entity.Salebill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
@Service
public class CostServiceImpl implements CostService {
    @Autowired
    SalebillRepository salebillRepository;
    @Override
    public Page<Salebill> findAllBy(QueryData queryData, Integer currentPage, Integer pageSize) {
        currentPage--;
        currentPage = currentPage < 0 ? 0 : currentPage;//page 为页码，数据库从0页开始
        //可以使用重载的 of(int page, int size, Sort sort) 方法指定排序字段
        Pageable pageable = PageRequest.of(currentPage, pageSize);

        Specification<Salebill> purspecification = new Specification<Salebill>() {
            @Override
            public Predicate toPredicate(Root<Salebill> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();

                if (queryData.getContractNum()!=null&&queryData.getContractNum()!="")
                    predicateList.add(criteriaBuilder.equal(root.get("contractNum").as(String.class),queryData.getContractNum()));
                if (queryData.getBillNum()!=null&&!"".equals(queryData.getBillNum()))
                    predicateList.add(criteriaBuilder.equal(root.get("billNum").as(String.class),queryData.getBillNum()));
                if (queryData.getStatus()!=null&&!"".equals(queryData.getStatus()))
                    predicateList.add(criteriaBuilder.equal(root.get("status").as(Integer.class),queryData.getStatus()));
                if (queryData.getCorrelationRatea()!=null&&!"".equals(queryData.getCorrelationRatea())&&queryData.getCorrelationRateb()!=null&&!"".equals(queryData.getCorrelationRateb()))
                    predicateList.add(criteriaBuilder.between(root.get("correlationRate").as(Double.class),queryData.getCorrelationRatea(),queryData.getCorrelationRateb()));



                Predicate[] predicates = new Predicate[predicateList.size()];
                return query.where(predicateList.toArray(predicates)).getRestriction();
            }
        };
        return salebillRepository.findAll(purspecification,pageable);//无数据时返回空列表;
    }
}
